from fastapi import APIRouter, Body, Depends
from sqlalchemy.orm import Session


from database import get_session, transactional_session
from mldong.auth_middleware import SaCheckPermission, SaMode
from mldong.base import R, CommonPage, CommonResult, IdParam, IdsParam
from mldong.user_context import UserContext
from modules.sys.params.user_param import UserPageParam, UserParam
from modules.sys.services.user_service import UserService
from modules.sys.vos.user_vo import UserVO

tags = ["用户"]
router = APIRouter(tags=tags)


def get_user_service(db: Session = Depends(get_session)) -> UserService:
    """
    获取用户服务实例的依赖函数
    """
    return UserService(db)


@router.post("/sys/user/save", summary="添加用户", response_model=CommonResult, response_model_exclude_none=True)
@SaCheckPermission("sys:user:save")
async def user_save(data: UserParam = Body(description="用户参数"), user_service: UserService = Depends(get_user_service)):
    with transactional_session(user_service.db):
        user_service.save(data)
    return R.success()


@router.post("/sys/user/update", summary="修改用户", response_model=CommonResult, response_model_exclude_none=True)
@SaCheckPermission("sys:user:update")
async def user_update(data: UserParam = Body(description="用户参数"), user_service: UserService = Depends(get_user_service)):
    with transactional_session(user_service.db):
        user_service.update(data)
    return R.success()


@router.post("/sys/user/remove", summary="删除用户", response_model=CommonResult, response_model_exclude_none=True)
@SaCheckPermission("sys:user:remove")
async def user_remove(param: IdsParam = Body(), user_service: UserService = Depends(get_user_service)):
    with transactional_session(user_service.db):
        user_service.remove_by_ids(param.ids)
    return R.success()


@router.post("/sys/user/detail", summary="用户详情", response_model=CommonResult[UserVO], response_model_exclude_none=True)
@SaCheckPermission(["sys:user:detail", "sys:user:update"], mode=SaMode.OR)
async def user_detail(param: IdParam = Body(), user_service: UserService = Depends(get_user_service)):
    data = user_service.detail(param.id)
    return R.data(data)


@router.post("/sys/user/page", summary="分页查询用户列表", response_model=CommonResult[CommonPage[UserVO]], response_model_exclude_none=True)
@SaCheckPermission("sys:user:page")
async def user_page(param: UserPageParam = Body(), user_service: UserService = Depends(get_user_service)):
    data = user_service.page(param)
    return R.data(data)




@router.post("/sys/user/info", summary="获取当前用户信息", response_model=CommonResult[UserVO], response_model_exclude_none=True)
async def user_info(user_service: UserService = Depends(get_user_service)):
    userId = UserContext.get_current_user_id()
    data = user_service.detail(userId)
    return R.data(data)